package lx;

import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.CaseInsensitiveContainerFactory;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.dialect.MysqlDialect;
import com.jfinal.plugin.druid.DruidPlugin;
import lx.dlh.Statistics;
import lx.util.ImageUtil;
import lx.util.OssUtil;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 * @Description: 定时器入口
 * @Author: 李星 lixing_java@163.com
 * @Date: 2020/3/13 22:00
 */
public class Application {
    private static final Log log = Log.getLog(Application.class);

    static {
        // 驱动
        String oracleDriverClass = "oracle.jdbc.driver.OracleDriver";
        String mysqlDriverClass = "com.mysql.cj.jdbc.Driver";

        // oracle数据库
        String oracleUrl = "jdbc:oracle:thin:@172.16.0.9:1521:HLKJORCL";
        String oracleUser = "hlkj_lix";
        String oraclePassword = "HLKJ#lix0311";

        // mysql数据库
        String mysqlUrl_master = "jdbc:mysql://192.168.71.134:3306/snoob?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&useSSL=false";
        String mysqlUser_master = "lixing";
        String mysqlPassword_master = "LI1234mysql!";

        // mysql数据库
        String mysqlUrl_slave = "jdbc:mysql://192.168.71.134:3306/snoob?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&useSSL=false";
        String mysqlUser_slave = "lixing";
        String mysqlPassword_slave = "LI1234mysql!";

        // 电老虎
        String mysqlUrl_dlh_dev = "jdbc:mysql://192.168.1.236:3306/etiger?serverTimezone=GMT%2b8&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull";
        String mysqlUser_dlh_dev = "dlh";
        String mysqlPassword_dlh_dev = "Dlh123456";

        String mysqlUrl_dlh_fat = "jdbc:mysql://192.168.1.236:3306/etigertest?serverTimezone=GMT%2b8&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull";
        String mysqlUser_dlh_fat = "dlh";
        String mysqlPassword_dlh_fat = "Dlh123456";

        String mysqlUrl_dlh_pro = "jdbc:mysql://rm-bp1cmog3d4dph8t88.mysql.rds.aliyuncs.com:3306/etiger?serverTimezone=GMT%2b8&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull";
        String mysqlUser_dlh_pro = "etiger";
        String mysqlPassword_dlh_pro = "Lhgy1321809#";

        String mysqlUrl_statistics_dev = "jdbc:mysql://192.168.213.141:3306/snoob_dev?serverTimezone=GMT%2b8&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false";
        String mysqlUser_statistics_dev = "lixing";
        String mysqlPassword_statistics_dev = "LI1234MYSQL!";

        /*
         * @Description TODO ActiveRecord概述：
         *  ActiveRecord 是 JFinal 最核心的组成部分之一，通过 ActiveRecord 来操作数据库，将极大地减少代码量，极大地提升开发效率
         *  ActiveRecord 模式的核心是：一个 Model 对象唯一对应数据库表中的一条记录，而对应关系依靠的是数据库表的主键值
         *  因此，ActiveRecord 模式要求数据库表必须要有主键。当数据库表没有主键时，只能使用 Db + Record 模式来操作数据库
         */
        /*
         * @Description TODO 数据库连接池的切换：
         * List<Record> recordList_master = Db.use("master").find("select * from sys_admin");
         * List<Record> recordList_slave = Db.use("slave").find("select * from sys_admin");
         */
//        DruidPlugin druidPlugin_master = new DruidPlugin(mysqlUrl_master, mysqlUser_master, mysqlPassword_master, mysqlDriverClass); // 通过druid数据源插件实例化数据库连接池
//        druidPlugin_master.start(); // 启动数据库连接池
//        ActiveRecordPlugin activeRecordPlugin_master = new ActiveRecordPlugin("master", druidPlugin_master); // 通过ActiveRecrod插件实例化数据库连接
//        activeRecordPlugin_master.setShowSql(false); // 不显示sql
//        activeRecordPlugin_master.setDialect(new MysqlDialect()); // 配置Oracle方言
//        activeRecordPlugin_master.setContainerFactory(new CaseInsensitiveContainerFactory()); // 配置属性名(字段名)大小写不敏感容器工厂
//        activeRecordPlugin_master.start(); // 启动数据库连接
//
//        DruidPlugin druidPlugin_slave = new DruidPlugin(mysqlUrl_slave, mysqlUser_slave, mysqlPassword_slave, mysqlDriverClass); // 通过druid数据源插件实例化数据库连接池
//        druidPlugin_slave.start(); // 启动数据库连接池
//        ActiveRecordPlugin activeRecordPlugin_slave = new ActiveRecordPlugin("slave", druidPlugin_slave); // 通过ActiveRecrod插件实例化数据库连接
//        activeRecordPlugin_slave.setShowSql(false); // 不显示sql
//        activeRecordPlugin_slave.setDialect(new MysqlDialect()); // 配置Oracle方言
//        activeRecordPlugin_slave.setContainerFactory(new CaseInsensitiveContainerFactory()); // 配置属性名(字段名)大小写不敏感容器工厂
//        activeRecordPlugin_slave.start(); // 启动数据库连接

        DruidPlugin druidPlugin_dlh_dev = new DruidPlugin(mysqlUrl_statistics_dev, mysqlUser_statistics_dev, mysqlPassword_statistics_dev, mysqlDriverClass); // 通过druid数据源插件实例化数据库连接池
        druidPlugin_dlh_dev.start(); // 启动数据库连接池
        ActiveRecordPlugin activeRecordPlugin_dlh_dev = new ActiveRecordPlugin("dev", druidPlugin_dlh_dev); // 通过ActiveRecrod插件实例化数据库连接
        activeRecordPlugin_dlh_dev.setShowSql(false); // 不显示sql
        activeRecordPlugin_dlh_dev.setDialect(new MysqlDialect()); // 配置数据库方言
        activeRecordPlugin_dlh_dev.setContainerFactory(new CaseInsensitiveContainerFactory()); // 配置属性名(字段名)大小写不敏感容器工厂
        activeRecordPlugin_dlh_dev.start(); // 启动数据库连接

        /*
         * @Description TODO 独创Db + Record模式，使用Db与Record类时，无需对数据库表进行映射，Record相当于一个通用的Model
         *
         * Record user = new Record().set("name", "James").set("age", 25); // 创建name属性为James,age属性为25的record对象并添加到数据库
         * Db.save("user", user);
         *  // Oracle并未直接支持自增主键，JFinal为此提供了便捷的解决方案。.nextval后缀一定要是小写，OracleDialect对该值的大小写敏感
         *  Record user = new Record().set("id", "MY_SEQ.nextval").set("age", 25);
         *  user.save();
         *  Integer id = user.get("id");
         *
         * // 事务处理
         * boolean succeed = Db.tx(new IAtom(){
         *   public boolean run() throws SQLException {
         *      int count = Db.update("update account set cash = cash - ? where id = ?", 100, 123);
         *      int count2 = Db.update("update account set cash = cash + ? where id = ?", 100, 456);
         *      return count == 1 && count2 == 1; 执行过程中发生异常或者run()方法返回false，则自动回滚事务
         *   }
         * }
         *
         * // 删除
         * Db.deleteById("user", 25); // 删除id值为25的user表中的记录
         *  // 复合主键
         *  Db.deleteByIds("user_role", "roleId, userId", 123, 456);
         *
         * // Db.findById
         * Record user = Db.findById("user", 25); // 查询id值为25的Record
         * Record user = Db.findById("user", userId, 25); // 查询userId值为25的Record
         *
         * // Db.findByIds
         * Record user = Db.findByIds("user_role", "roleId, userId", 123, 456); // 复合主键
         *
         * // Db.find
         * List<Record> users = Db.find("select * from user where age > 18"); // 查询所有年龄大于18岁的user
         *
         * // Db.query
         * List<String> title = Db.query("select title from blog");
         * List<Object[]> list = Db.query("select id, title, content from blog");
         *
         * // Db.queryXxx
         * int total = Db.queryInt("select vcount(*) from account");
         * String nickName = Db.queryStr("select nickName from account where id = ?", 123);
         *
         * // Db.paginate
         * Page<Record> userPage = Db.paginate(1, 10, "select *", "from user where age > ?", 18); // 分页查询所有年龄大于18岁的user
         */
    }

    //length用户要求产生字符串的长度
    public static String getRandomString(int length){
        String str= "Java 是一门面向对象编程语言，不仅吸收了 C++ 语言的各种优点，还摒弃了 C++ 里难以理解的多继承、指针等概念。Java 不但可以用来开发网站后台、PC 客户端和 Android APP，还在数据分析、网络爬虫、云计算领域大显身手";
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<length;i++){
            int number=random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    public static String getPrice(){
        Double price = new Random().nextDouble() * 1000;
        return new DecimalFormat("#.00").format(price);
    }

    public static Integer getCategory(){
        Integer[] locationArray = new Integer[]{10,20,30,40,50,60,70,80,90};
        int locationArrayLength = locationArray.length;
        return locationArray[new Random().nextInt(locationArrayLength)];
    }

    public static Integer getLocation(){
        Integer[] locationArray = new Integer[]{100,200,300,400,500,600,700,800,900};
        int locationArrayLength = locationArray.length;
        return locationArray[new Random().nextInt(locationArrayLength)];
    }

    /*
     * @Description TODO JAVA内置定时器框架Timer
     *  Timer适用于大规模并发调度定时任务，在内部，该类使用二进制的堆表示其定时任务队列
     *
     *  void schedule(TimerTask task, long delay) 在delay毫秒之后调度任务执行
     *  void schedule(TimerTask task, Date time) 在某个时间点调度任务执行
     *  void schedule(TimerTask task, long delay, long period) 在delay毫秒之后调度任务开始执行，以固定时间间隔的方式重复执行，后续将一大约period毫秒的固定时间间隔执行
     *  void schedule(TimerTask task, Date firstTime, long period) 调度任务于firstTime开始，以固定时间间隔的方式重复执行，后续将一大约period毫秒的固定时间间隔执行
     *  void scheduleAtFixedRate(TimerTask task, long delay, long period) 在delay毫秒之后，开始调度任务以固定速率的方式重复执行，后续将以大约period毫秒数的固定时间间隔执行
     *  void scheduleAtFixedRate(TimerTask task, Date firstTime,long period) 调度任务于firstTime开始，以固定速率的方式重复执行，后续将大约period毫秒数的固定时间间隔执行
     *  sched(TimerTask task, long time, long period) 在指定时间执行调度任务执行，以固定时间间隔的方式重复执行，后续将一大约period毫秒的固定时间间隔执行
     *  void cancel() 终止定时器，丢弃所有当前调度的定时器任务。不干涉当前正在执行的任务，能保证正在执行的任务一定是最后一个被该定时器执行的任务
     *  int purge() 从该定时器队列中移除所有取消的定时任务并且返回被移除任务的数目
     */
    public static void main(String[] args) {
        log.info("========进入主方法========");
        String phoneSource = "18013896707";

        // 1000000
        // 1999999
        // 3000000
        // 4000000
        // 5000000
        // 6000000
        for (int i = 6000001; i < 10000001 ; i++) {
            Record orderCount = new Record()
                    .set("user_id", System.currentTimeMillis() + i)
                    .set("user_name", getRandomString(4))
                    .set("user_province", getCategory())
                    .set("user_city", getCategory())
                    .set("order_id", System.currentTimeMillis() + i)
                    .set("order_price", getPrice())
                    .set("product_id", System.currentTimeMillis() + i)
                    .set("product_category", getCategory())
                    .set("product_loaction", getLocation())
                    .set("create_time", new Date());
            boolean flag = Db.save("order_count", orderCount);
            log.info(i + "_" + flag);
        }


        /*
         * @Description TODO Token
         *               nohup java -jar token.jar > token.log &
         * @Author 李星
         * @Date 2020/3/24 19:24
         * @Param [args]
         * @return void
         */
        //        timer.schedule(new HlkjTokenTask(), 1000, 1000*60*60); // 【汇龙科技线上token】
        //        timer.schedule(new HnTokenTask(), 1000*60, 1000*60*60); // 【湖南线上token】
        //        timer.schedule(new XjTokenTask(), 1000, 1000*60*60); // 【新疆线上token】

        /*
         * @Description TODO 部门、成员、客户信息同步
         *               nohup java -jar DepartmentTask.jar > DepartmentTask.log &
         *               nohup java -jar UserTask.jar > UserTask.log &
         *               nohup java -jar CustomerTask.jar > CustomerTask.log &
         *
         * @Author 李星
         * @Date 2020/3/24 19:25
         * @Param [args]
         * @return void
         */
//        timer.schedule(new DepartmentTask(), 17000, 1000*60*60*24);
//        timer.schedule(new UserTask(), 1000, 1000*60*60*24);
//        timer.schedule(new CustomerTask(), 1000, 1000*60*60*24);

        /*
         * @Description TODO 成员、客户消息
         *               nohup java -jar MessageStaffTask.jar > MessageStaffTask.log &
         *               nohup java -jar MessageCustomerTask.jar > MessageCustomerTask.log &
         * @Author 李星
         * @Date 2020/3/24 19:25
         * @Param [args]
         * @return void
         */
//        timer.schedule(new MessageStaffTask(), 1000, 1000*10); // 新疆成员消息推送
//        timer.schedule(new MessageCustomerTask(), 1000, 1000*10); // 新疆客户消息推送

//        // 图片宽高度读取并刷新 pic_properties
//        List<Record> coCompanyPicList = Db.find("select id,pic_path from co_company_pic order by id asc");
//        coCompanyPicList.forEach(item -> {
//            String picPath = item.getStr("pic_path");
//            if (null != picPath && picPath.length() > 0) {
//                try {
//                    BufferedImage pic = ImageIO.read(new URL(picPath));
//                    JSONObject picPropertiesObj = new JSONObject();
//                    picPropertiesObj.put("picWidth", pic.getWidth());
//                    picPropertiesObj.put("picHeight", pic.getHeight());
//                    //
//                    Record coCompanyPicRecord = new Record();
//                    coCompanyPicRecord.set("id", item.getLong("id"));
//                    coCompanyPicRecord.set("pic_properties", picPropertiesObj.toJSONString());
//                    Db.update("co_company_pic", "id", coCompanyPicRecord);
//                    //
//                    log.info(MessageFormat.format("视频id: {0} 读取成功：{1}", String.valueOf(item.getLong("id")), picPropertiesObj.toJSONString()));
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        });

        // OSS 生产环境参数
//        String browsePath = "https://etiger.oss-cn-hangzhou.aliyuncs.com/";
//        String endpoint = "oss-cn-hangzhou.aliyuncs.com";
//        String accessKeyId = "LTAI4GFfae2Jima78R3cMnuU";
//        String accessKeySecret = "kzjDcWPKJLfPDUWYvPu8dvdmObFNZO";
//        String bucketName = "etiger";
        // OSS 测试数据
//        String browsePath = "https://etigertest.oss-cn-hangzhou.aliyuncs.com/";
//        String endpoint = "oss-cn-hangzhou.aliyuncs.com";
//        String accessKeyId = "LTAI4GFfae2Jima78R3cMnuU";
//        String accessKeySecret = "kzjDcWPKJLfPDUWYvPu8dvdmObFNZO";
//        String bucketName = "etigertest";

        // 企业资料数据刷取
//        List<Record> co_company_video_temp = Db.find("select id,file_path from co_company_library_temp");
//        log.info("co_company_library_temp -- "+ co_company_video_temp.size());
//        co_company_video_temp.forEach(item -> {
//            String fileKey = new SimpleDateFormat("yyyy/MM/dd/").format(new Date()) + UUID.randomUUID().toString().replaceAll("-", "") + ".png";
//            BufferedImage bufferedImage;
//            try {
//                String cover_path = OssUtil.getVideoCover(item.getStr("video_path"), "png", 0, 0);
//                bufferedImage = ImageIO.read(new URL(cover_path));
//                InputStream videoCoverImageInputStream = ImageUtil.getInputStreamFromBufferedImage(bufferedImage, "png");
//                OssUtil.putObject(bucketName, endpoint, accessKeyId, accessKeySecret, videoCoverImageInputStream, fileKey);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            Record record = new Record();
//            record.set("id", item.getLong("id"));
//            record.set("cover_img", browsePath + fileKey);
//            boolean flag = Db.update("co_company_video_temp", "id", record);
//            log.info(flag + " 更新 " + record.getLong("id") + " 的cover_img 为：" + record.getStr("cover_img"));
//        });

        // 企业视频数据刷取
//        List<Record> co_company_video_temp = Db.find("select id,video_path from co_company_video_temp");
//        log.info("co_company_video_temp -- "+ co_company_video_temp.size());
//        co_company_video_temp.forEach(item -> {
//            String fileKey = new SimpleDateFormat("yyyy/MM/dd/").format(new Date()) + UUID.randomUUID().toString().replaceAll("-", "") + ".png";
//            BufferedImage bufferedImage;
//            try {
//                String cover_path = OssUtil.getVideoCover(item.getStr("video_path"), "png", 0, 0);
//                bufferedImage = ImageIO.read(new URL(cover_path));
//                InputStream videoCoverImageInputStream = ImageUtil.getInputStreamFromBufferedImage(bufferedImage, "png");
//                OssUtil.putObject(bucketName, endpoint, accessKeyId, accessKeySecret, videoCoverImageInputStream, fileKey);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            Record record = new Record();
//            record.set("id", item.getLong("id"));
//            record.set("cover_img", browsePath + fileKey);
//            boolean flag = Db.update("co_company_video_temp", "id", record);
//            log.info(flag + " 更新 " + record.getLong("id") + " 的cover_img 为：" + record.getStr("cover_img"));
//        });

//        List<Record> ol_factory_temp = Db.find("select id,video_path from ol_factory_temp");
//        log.info("ol_factory_temp -- "+ ol_factory_temp.size());
//        ol_factory_temp.forEach(item -> {
//            String fileKey = new SimpleDateFormat("yyyy/MM/dd/").format(new Date()) + UUID.randomUUID().toString().replaceAll("-", "") + ".png";
//            BufferedImage bufferedImage;
//            try {
//                String cover_path = OssUtil.getVideoCover(item.getStr("video_path"), "png", 0, 0);
//                bufferedImage = ImageIO.read(new URL(cover_path));
//                InputStream videoCoverImageInputStream = ImageUtil.getInputStreamFromBufferedImage(bufferedImage, "png");
//                OssUtil.putObject(bucketName, endpoint, accessKeyId, accessKeySecret, videoCoverImageInputStream, fileKey);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            Record record = new Record();
//            record.set("id", item.getLong("id"));
//            record.set("cover_img", browsePath + fileKey);
//            boolean flag = Db.update("ol_factory_temp", "id", record);
//            log.info(flag + " 更新 " + record.getLong("id") + " 的cover_img 为：" + record.getStr("cover_img"));
//        });

//        List<Record> ol_project_temp = Db.find("select id,video_path from ol_project_temp");
//        log.info("ol_project_temp -- "+ ol_project_temp.size());
//        ol_project_temp.forEach(item -> {
//            String fileKey = new SimpleDateFormat("yyyy/MM/dd/").format(new Date()) + UUID.randomUUID().toString().replaceAll("-", "") + ".png";
//            BufferedImage bufferedImage;
//            try {
//                String cover_path = OssUtil.getVideoCover(item.getStr("video_path"), "png", 0, 0);
//                bufferedImage = ImageIO.read(new URL(cover_path));
//                InputStream videoCoverImageInputStream = ImageUtil.getInputStreamFromBufferedImage(bufferedImage, "png");
//                OssUtil.putObject(bucketName, endpoint, accessKeyId, accessKeySecret, videoCoverImageInputStream, fileKey);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            Record record = new Record();
//            record.set("id", item.getLong("id"));
//            record.set("cover_img", browsePath + fileKey);
//            boolean flag = Db.update("ol_project_temp", "id", record);
//            log.info(flag + " 更新 " + record.getLong("id") + " 的cover_img 为：" + record.getStr("cover_img"));
//        });

    }


}
